package org.peoples.clients;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.red5.server.api.IClient;
import org.red5.server.api.IConnection;

public class ClientPool {
	
	private volatile static ClientPool instance;
	
	private HashMap<Integer, User> users;
	private HashMap<Integer, IClient> clients;
	private HashMap<IClient, User> clientUsers;
	
	//private HashMap<int[], User> users;
	
	private int userCount;
	
	
	private ClientPool() {
		
		this.users = new HashMap<Integer, User> ();
		this.clients = new HashMap<Integer, IClient> ();
		this.clientUsers = new HashMap<IClient, User> ();
		this.userCount = 0;
		
	}
	
	
	public User addClient(String firstName, String lastName, Date time, IClient client) {
		if (!users.containsValue(client)) {
			int id = userCount++;
			
			User user = new User();
			user.firstName = firstName;
			user.lastName = lastName;
			user.time = time;
			user.ID = id;
			user.streamID = "stream_" + id;
			
			users.put(id, user);
			clients.put(id, client);
			clientUsers.put(client, user);
			
			return user;
		}
		
		return null;
	}

	public Collection<IClient> getAllClients() {
		return clients.values();
	}
	
	public Collection<User> getAllUsers() {
		return users.values();
	}
	
	public IClient getClient(User user) {
		return clients.get(user.ID);
	}
	
	public User getUser(int id) {
		return users.get(id);
	}
	
	public User getUser(IClient client) {
		return clientUsers.get(client);
	}
	
	public Set<IConnection> getConnections() {
		
		HashSet<IConnection> connections = new HashSet<IConnection> ();
		Iterator<IClient> itr = clients.values().iterator();
		
		while (itr.hasNext()) {
			connections.addAll(itr.next().getConnections());
		}
		
		return connections;
		
	}
	
	public static ClientPool getInstance() {
		if (instance == null) {
			synchronized (ClientPool.class) {
				if (instance == null)
					instance = new ClientPool();
			}
		}
		
		return instance;
	}
	
	public boolean isEmpty() {
		return size() == 0;
	}
	
	public IClient removeClient(User user) {
		users.remove(user.ID);
		
		IClient client = clients.remove(user.ID);
		clientUsers.remove(client);
		return client;
	}
	
	public int size() {
		return users.size();
	}
	
	public String toString() {
		return users.toString();
	}
	
}
